const {Router} = require('express')
let router = new Router()
let bodyParser = require("body-parser");
const commentModel = require('../models/commentModel')

router.get('/commentInfo',async (req,res) => {
    const {aid} = req.query
    if(aid){
        let commentInfo = await commentModel.find({"belong":aid})
        if(commentInfo){
            res.send({success:true,data:commentInfo})
        }else{
            res.send({success:false,message:'查询失败'})
        }
    }else{
        let commentInfo = await commentModel.find()
        if(commentInfo){
            res.send({success:true,data:commentInfo})
        }else{
            res.send({success:false,message:'查询失败'})
        }
    }    
})

router.post('/createNewComment', bodyParser.json(), async (req,res) => {
    const {belong, comment_content, user_id, create_time} = req.body
    let cid = 'c' + Date.now()
    let commentInfo = await commentModel.create({cid, comment_content, user_id, belong, create_time})
    if(commentInfo) {
        res.send({success:true, message:'评论成功', data:commentInfo})
    }else{
        res.send({success:false, message:'评论失败'})
    }
})

// 删除留言
router.get('/commentDelete', async (req, res) => {
    const { cid } = req.query
    try {
        let result = await commentModel.deleteOne(cid)
        res.send({ success: true, message: '删除成功', data: result })
    } catch (e) {
        res.send({ success: false, message: e })
    }
})


module.exports = router